#include "client.h"
#include <QtCore/QDebug>
#include <QtCore/QRegExp>

Client::Client(QString email, QString password)
{
    m_email = email;
    m_password = password;
    logging = false;
    logged = false;
    checking = false;
    // Creating http-client
    m_http = new HttpClient("pda.vkontakte.ru", 80);
    connect(m_http, SIGNAL(requestDone(QByteArray*)), this, SLOT(httpRequestDone(QByteArray*)));
    connect(m_http, SIGNAL(requestError(QString)), this, SLOT(httpRequestError(QString)));
}

Client::~Client()
{
    delete m_http;
}

void Client::setAuthInfo(QString email, QString password)
{
    m_email = email;
    m_password = password;
    logged = false;
}

void Client::setConnectionInfo(QString host, int port)
{
    m_http->setConnectionInfo(host, port);
}

void Client::setProxyInfo(bool useProxy, QString proxyHost, int proxyPort,
                  bool useProxyAuth, QString proxyUser, QString proxyPass)
{
    m_http->setProxyInfo(useProxy, proxyHost, proxyPort,
                         useProxyAuth, proxyUser, proxyPass);
}

void Client::login()
{
    m_http->m_cookies = "";
    QString content("email="+m_email+"&pass="+m_password);
    logging = true;
    m_http->doRequest("/login?pda=index&acknowledge=0",
                      content.toUtf8());
}

void Client::check()
{
    if (!logged)
    {
        if (!logging)
            login();
        needCheck = true;
        return;
    }
    checking = true;
    qsrand(NULL);
    m_http->doRequest("/?"+QString::number(qrand()%20000, 10));
}

void Client::httpRequestDone(QByteArray *data)
{
    if (logging)
    {
        if (m_http->m_cookies.indexOf("remixpass") != -1)
        {
            qDebug() << "Logged in!";
            logged = true;
            if (needCheck)
                check();
        }
        else if (m_http->response == 302)
            emit error(tr("Invalid login or password"));
        else
            emit error(tr("Error while logging"));
        logging = false;
    }
    else if (checking)
    {
        if (m_http->response != 200)
        {
            emit error(tr("Unexpected response (%1 %2)").arg(QString::number(m_http->response), m_http->responseMsg));
            return;
        }

        QRegExp re("<a href=\"/inbox\">(.*)</a>", Qt::CaseInsensitive);
        re.setMinimal(true);
        int pos = re.indexIn(*data);
        if (pos > -1)
        {
            QString msg = re.cap(1);
            re = QRegExp("<b>([^>]*)</b>");
            pos = re.indexIn(msg);
            if (pos > -1)
                emit messagesCount(re.cap(1).toInt());
            else
                emit messagesCount(0);
        }
        else
            emit error(tr("Error while parsing personal page"));
    }
}

void Client::httpRequestError(QString message)
{
    logging = false;
    checking = false;
    emit error(tr("Connection error (%1)").arg(message));
}
